package com.javabasic.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see
 * @since Created by work on 2022/6/21 21:58
 */
public class EncodeAndDecodeTinyURL {

}
class Codec {

    private final String shortUrlLetters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private final String shortUrlPrefix = "http://mir-url/";
    private final int SHORT_LETTER_NUM = 6;
    private Map<String, String> shortUrlToOriginUrlMap = new HashMap<>(16);
    private final Random random = new Random();


    /**
     * 加密解密算法+映射关系存储
     * @param longUrl
     * @return
     */
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        StringBuffer shortLetters = new StringBuffer();
        while (true) {
            for (int i = 0; i < SHORT_LETTER_NUM; i++) {
                shortLetters.append(shortUrlLetters.charAt(random.nextInt(62)));
            }
            if (!shortUrlToOriginUrlMap.containsKey(shortLetters.toString())) {
                System.out.println(shortLetters.toString());
                shortUrlToOriginUrlMap.put(shortLetters.toString(),longUrl);
                break;
            }
            shortLetters.delete(0, SHORT_LETTER_NUM);
        }
        return shortUrlPrefix + shortLetters;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        String[] split = shortUrl.split("/");
        int len = split.length;
        return shortUrlToOriginUrlMap.get(split[len-1]);
    }
}